package com.fxnotes.common.ui;



import javafx.event.EventHandler;
import javafx.scene.control.ListCell;
import javafx.scene.control.ListView;
import javafx.scene.control.TextField;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.util.Callback;

public abstract class ListCallback<T> implements Callback<ListView<T>, ListCell<T>> {

    @Override
    public ListCell<T> call(final ListView<T> listView) {
        final TextField textField = new TextField();

        final EditableListCell<T> listCell = new EditableListCell<T>(textField) {

            @Override
            public String getString(T item) {
                return ListCallback.this.getString(item);
            }

            @Override
            public void changed(T item) {
                ListCallback.this.changed(item);
            }
        };
        textField.setOnKeyPressed(new EventHandler<KeyEvent>() {

            @Override
            public void handle(KeyEvent event) {
                if (event.getCode() == KeyCode.ENTER) {
                    T item = (T) listView.getSelectionModel().getSelectedItem();
                    updateItem(item, textField.getText());
                    listCell.commitEdit(item);

                } else if (event.getCode() == KeyCode.ESCAPE) {
                    listCell.cancelEdit();
                }
            }
        });

        return listCell;
    }

    public abstract void updateItem(T item, String value);

    public abstract String getString(T item);

    public abstract void changed(T item);
}
